package com.aqie.counter.controller;

import com.aqie.counter.bean.res.*;
import com.aqie.counter.cache.StockCache;
import com.aqie.counter.service.IOrderService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.List;

import static com.aqie.counter.bean.res.R.*;

@RestController
@RequestMapping("/api")
@Log4j2
public class OrderController {

    @Autowired
    private StockCache stockCache;

    @RequestMapping("/code")
    public R sotckQuery(@RequestParam String key) {
        Collection<StockInfo> stocks = stockCache.getStocks(key);
        return new R(stocks);
    }


    @Autowired
    private IOrderService orderService;


    @RequestMapping("/balance")
    public R balanceQuery(@RequestParam long uid)
            throws Exception {
        long balance = orderService.getBalance(uid);
        return new R(balance);
    }

    @RequestMapping("/posiinfo")
    public R posiQuery(@RequestParam long uid)
            throws Exception {
        List<PosiInfo> postList = orderService.getPostList(uid);
        return new R(postList);
    }

    @RequestMapping("/orderinfo")
    public R orderQuery(@RequestParam long uid)
            throws Exception {
        List<OrderInfo> orderList = orderService.getOrderList(uid);
        return new R(orderList);
    }

    @RequestMapping("/tradeinfo")
    public R tradeQuery(@RequestParam long uid)
            throws Exception {
        List<TradeInfo> tradeList = orderService.getTradeList(uid);
        return new R(tradeList);
    }

    @RequestMapping("/sendorder")
    public R order(
            @RequestParam int uid,
            @RequestParam short type,
            @RequestParam long timestamp,
            @RequestParam int code,
            @RequestParam byte direction,
            @RequestParam long price,
            @RequestParam long volume,
            @RequestParam byte ordertype
    ) {
        if (orderService.sendOrder(uid, type, timestamp, code, direction, price,
                volume, ordertype)) {
            return new R(SUCCESS, "save success", null);
        } else {
            return new R(FAIL, "save failed", null);
        }

    }

    @RequestMapping("/cancelorder")
    public R cancelOrder(@RequestParam int uid,
                         @RequestParam int counteroid,
                         @RequestParam int code) {

        if (orderService.cancelOrder(uid, counteroid, code)) {
            return new R(SUCCESS, "success", null);
        } else {
            return new R(FAIL, "failed", null);
        }
    }


}
